<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ws模块实现websocket</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="padding:10px">
    <form style="width:520px; margin-bottom:10px">
        <input class="form-control" type="text" style="margin-bottom:10px">
        <button  type="button" class="btn btn-primary">点击发送</button>
        <button type="button" class="btn btn-danger">点击关闭</button>
    </form>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
        var ws = new WebSocket('ws://localhost:8181')
        ws.onopen = function(e){
            console.log('开始连接服务器')
            $('.btn-primary').click(function(){
                ws.send($('.form-control').val())
                $('.form-control').val('')
             })
             ws.onmessage = function(msg){
                $('body').append('<p>'+ msg.data +'</p>')
             }
             $('.btn-danger').click(function(){
                ws.close()
             })
        }
        
    </script>
</body>
</html>